package userUI;

import handler.CreateTableHandler;
import handler.FileHandler;
import handler.ImportDataHandler;
import pojo.InventoryInfo;
import pojo.Transaction;

import java.io.*;
import java.sql.*;
import java.util.*;

import static Util.JdbcUtil.getConnection;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.sql.*;
import java.util.List;

public class MainApplication extends JFrame {
    private JTextField inboundField;
    private JTextField outboundField;
    private JTextArea logArea;
    private String directoryPath;
    public MainApplication() {
        setTitle("简易订货系统");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(600, 400);
        setLayout(new FlowLayout());

        // 创建按钮
        JButton createTableButton = new JButton("创建表");
        //选中目录按钮
        JButton selectDirectoryButton = new JButton("选择目录");
        JButton insertDataButton = new JButton("插入数据");


        JButton inOutButton = new JButton("出入库");
        JButton reportButton = new JButton("产生报表");

        // 输入字段
        inboundField = new JTextField("", 20);
        outboundField = new JTextField("", 20);

        // 日志显示区域
        logArea = new JTextArea(10, 50);
        logArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(logArea);

        setLayout(new FlowLayout()); // Or whatever layout you're currently using

// Add buttons in a single line
        add(createTableButton);
        add(selectDirectoryButton);
        add(insertDataButton);
        add(inOutButton);
        add(reportButton);

// Wrap "warehousing quantity" components in a new JPanel
        JPanel warehousingPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); // Align to the left
        warehousingPanel.add(new JLabel("入库数量:"));
        warehousingPanel.add(inboundField);
        warehousingPanel.add(new JLabel("出库数量:"));
        warehousingPanel.add(outboundField);

        add(warehousingPanel); // Add the new panel to the container

// Add the scroll pane in a separate row
        add(scrollPane);


        // 按钮事件绑定
        createTableButton.addActionListener(e -> createTables());
        selectDirectoryButton.addActionListener(e -> selectDirectory());
        insertDataButton.addActionListener(e -> insertData());
        inOutButton.addActionListener(e -> {
            try {
                transactionHandler();
            } catch (SQLException ex) {
                logArea.append("出入库处理失败: " + ex.getMessage() + "\n");
            }
        });
        reportButton.addActionListener(e -> reportList());

        setVisible(true);
    }

    /**
     * 创建数据库表
     */
    private void createTables() {
        CreateTableHandler.createTables();
        logArea.append("创建库存信息表inventory表成功！\n");
        logArea.append("创建订单信息表orderinfo表成功！\n");
        logArea.append("创建事务表transaction表成功！\n");
    }

    /**
     * 选择目录
     */
    private void selectDirectory() {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int result = fileChooser.showOpenDialog(this);
        if (result == JFileChooser.APPROVE_OPTION) {
            File selectedDirectory = fileChooser.getSelectedFile();
            directoryPath=selectedDirectory.getAbsolutePath();
            logArea.append("选择的目录: " + selectedDirectory.getAbsolutePath() + "\n");
        }
    }
    /**
     * 插入测试数据
     */
    private void insertData() {

        if(directoryPath=="")
        {
            logArea.append("请先选择目录\n");
            return;
        }
        // 调用ImportDataHandler类中的方法将数据文件inventory_info.txt中的数据插入到库存信息inventoryinfo表中
        List<InventoryInfo> inventoryList = FileHandler.inventoryFileHandler(directoryPath);
        //将插入的数据信息添加到logArea中
        for (InventoryInfo inventoryInfo : inventoryList) {
            logArea.append(inventoryInfo.toString()+"\n");
        }
        //将插入的数据信息添加到logArea中
        int rowsInserted = ImportDataHandler.insertInventoryInfo(inventoryList);
        //将transaction.txt中的数据插入到事务表transaction中
        List<Transaction> transactionList = FileHandler.transactionFileHandler(directoryPath);
        for (Transaction transaction : transactionList) {
            logArea.append(transaction.toString()+"\n");
        }
        //将transaction.txt中的数据插入到事务表transaction中
        int rowsInserted2 = ImportDataHandler.insertTransaction(transactionList);

    }

    /**
     * 出入库逻辑
     */
    private void transactionHandler() throws SQLException {
        try (Connection connection = getConnection()) {
            connection.setAutoCommit(false);

            String queryTransactions = "SELECT * FROM transaction WHERE UpdateStatus = 0";
            try (PreparedStatement ps = connection.prepareStatement(queryTransactions);
                 ResultSet rs = ps.executeQuery()) {

                int totalInbound = 0, totalOutbound = 0;

                while (rs.next()) {
                    String partNumber = rs.getString("PartNumber");
                    String transactionType = rs.getString("TransactionType");
                    int quantity = rs.getInt("Quantity");
                    String transactionNumber = rs.getString("TransactionNumber");
                    //打印出事务信息
                    //logArea.append("事务信息: " + transactionNumber + ", 零件编号: " + partNumber + ", 交易类型: " + transactionType + ", 数量: " + quantity + "\n");
                    if ("Inbound".equals(transactionType)) {
                        updateInventory(connection, partNumber, quantity, true);
                        totalInbound += quantity;
                    } else if ("Outbound".equals(transactionType)) {
                        updateInventory(connection, partNumber, quantity, false);
                        totalOutbound += quantity;
                    }
                    updateTransactionStatus(connection, transactionNumber, partNumber);
                }

                generateOrderInfo(connection);
                connection.commit();

                inboundField.setText(String.valueOf(totalInbound));
                totalOutbound=-totalOutbound;
                outboundField.setText(String.valueOf(totalOutbound));
                //logArea.append("出入库处理完成！\n");
            } catch (SQLException e) {
                connection.rollback();
                throw e;
            }
        }
    }

    private void updateInventory(Connection connection, String partNumber, int quantity, boolean isInbound) throws SQLException {
        String updateQuery = isInbound
                ? "UPDATE inventoryinfo SET InventoryQuantity = InventoryQuantity + ? WHERE PartNumber = ?"
                : "UPDATE inventoryinfo SET InventoryQuantity = InventoryQuantity - ? WHERE PartNumber = ?";
        try (PreparedStatement ps = connection.prepareStatement(updateQuery)) {
            ps.setInt(1, quantity);
            ps.setString(2, partNumber);
            ps.executeUpdate();
            //日志输出格式已更新库存信息表1行，更新的零件编号是PartNumber
            logArea.append("更新库存信息表" + 1 + "行，更新的零件编号是" + partNumber + "\n");
        }
    }

    private void updateTransactionStatus(Connection connection, String transactionNumber,String partNumber) throws SQLException {

        String updateTransaction = "UPDATE transaction SET UpdateStatus = 1 WHERE TransactionNumber = ?";
        try (PreparedStatement ps = connection.prepareStatement(updateTransaction)) {
            ps.setString(1, transactionNumber);

            ps.executeUpdate();
            //日志输出格式已更新事务表1行，更新的零件编号是PartNumber
            logArea.append("更新事务表" + 1 + "行，更新的零件编号是" + partNumber + "\n");
        }
    }

    private void generateOrderInfo(Connection connection) throws SQLException {
    /*
    当完成出入库后，将要订货的零件信息记录在订货信息表中。
    */
        String queryCriticalParts = "SELECT PartNumber, PartName, InventoryQuantity, CriticalValue FROM inventoryinfo WHERE InventoryQuantity < CriticalValue";

        try (PreparedStatement ps = connection.prepareStatement(queryCriticalParts)) {
            try (ResultSet rs = ps.executeQuery()) {
                while (rs.next()) {
                    String partNumber = rs.getString("PartNumber");
                    String partName = rs.getString("PartName");
                    int inventoryQuantity = rs.getInt("InventoryQuantity");
                    double criticalValue = rs.getDouble("CriticalValue");
                    int orderQuantity = (int) Math.ceil(criticalValue - inventoryQuantity);

                    // 使用 ON DUPLICATE KEY UPDATE 实现插入或更新
                    String insertOrUpdateOrderInfo =
                            "INSERT INTO orderinfo (PartNumber, PartName, OrderQuantity, CurrentPrice, MainSupplier, TimesSupplier) " +
                                    "VALUES (?, ?, ?, ?, ?, ?) " +
                                    "ON DUPLICATE KEY UPDATE " +
                                    "OrderQuantity = VALUES(OrderQuantity), " +
                                    "CurrentPrice = VALUES(CurrentPrice), " +
                                    "MainSupplier = VALUES(MainSupplier), " +
                                    "TimesSupplier = VALUES(TimesSupplier)";

                    try (PreparedStatement insertPS = connection.prepareStatement(insertOrUpdateOrderInfo)) {
                        insertPS.setString(1, partNumber);
                        insertPS.setString(2, partName);
                        insertPS.setInt(3, orderQuantity);
                        insertPS.setDouble(4, 0.0); // 设置默认价格
                        insertPS.setString(5, "X1");  // 设置默认供应商
                        insertPS.setString(6, "X2");  // 设置默认供应商时间
                        insertPS.executeUpdate();
                        logArea.append("生成订单信息: 零件编号: " + partNumber + ", 零件名称: " + partName + ", 订货数量: " + orderQuantity + "\n");
                    } catch (SQLException e) {
                        // 处理异常
                        logArea.append("生成订单信息失败: " + e.getMessage() + "\n");
                    }
                }
            }
        }
    }


    private void reportList() {
        try (Connection connection = getConnection();
             PreparedStatement ps = connection.prepareStatement("SELECT * FROM orderinfo ORDER BY PartNumber");
             ResultSet rs = ps.executeQuery();
             BufferedWriter writer = new BufferedWriter(new FileWriter(directoryPath+"/report_list.txt"));
             BufferedWriter writer2 = new BufferedWriter(new FileWriter(directoryPath+"/order_info.txt"))) {
            writer.write("PartNumber,PartName,OrderQuantity,CurrentPrice,MainSupplier,TimesSupplier\n");
            writer2.write("PartNumber,PartName,OrderQuantity,CurrentPrice,MainSupplier,TimesSupplier\n");
            while (rs.next()) {
                writer.write(String.format("%s,%s,%d,%.2f,%s,%s\n",
                        rs.getString("PartNumber"),
                        rs.getString("PartName"),
                        rs.getInt("OrderQuantity"),
                        rs.getBigDecimal("CurrentPrice"),
                        rs.getString("MainSupplier"),
                        rs.getString("TimesSupplier")));
            }
            // 打印日志

            logArea.append("报表生成完成！\n");

        } catch (SQLException | IOException e) {
            logArea.append("生成报表失败: " + e.getMessage() + "\n");
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(MainApplication::new);
    }
}

